﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Reflection;
using System.Data;
namespace WindowsService
{
    class ServiceEmail
    {

        private string PMSite = ConfigurationManager.AppSettings["PMSite"];
        public void SendDailyEmail(DateTime currentTime)
        {
            string Sql = "select a.*,b.projectcode from task a left join project b on a.projectid=b.id and b.IsActived =1 inner join TaskState c on a.TaskStateID=c.id and c.code=30  where a.enddate<='" + currentTime.ToShortDateString() + "' order by b.projectcode,a.startdate";
            DataTable tasks= SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);
            List<string> ownerList = new List<string>();
            for (int i = 0; i < tasks.Rows.Count; i++)
            {
                string owner = tasks.Rows[i]["Owners"].ToString();
                List<string> temp = owner.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!ownerList.Contains(temp[k]))
                        ownerList.Add(temp[k]);
                }
            }
            for (int i = 0; i < ownerList.Count; i++)
            {
                int taskcount = 0;
                string toemail;
                string html = ownerhtml(ownerList[i], tasks, out taskcount, out toemail);
                if (taskcount>0)
                {
                    html = ownerList[i] + " 您好，截止" + currentTime.ToShortDateString() + " 24时，您共有" + taskcount.ToString() + "个过期未完成任务<br/>" + html;
                    html += "<br/>" + "<a href='" + PMSite + "'>" + "点击查看" + "</a>";
                    SendEmail(toemail, ownerList[i], "每日邮件提醒", html);
                }
            }
            Sql = "select a.*,b.manager,b.projectcode from task a inner join project b on a.projectid=b.id and b.IsActived =1  inner join TaskState c on a.TaskStateID=c.id and c.code=30  where a.enddate<='" + currentTime.ToShortDateString() + "'  order by b.projectcode,a.startdate";
            tasks = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);
            List<string> managerList = new List<string>();
            for (int i = 0; i < tasks.Rows.Count; i++)
            {
                string manager = tasks.Rows[i]["manager"].ToString().ToUpper();
                List<string> temp = manager.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!managerList.Contains(temp[k]))
                        managerList.Add(temp[k]);
                }
            }
            for (int i = 0; i < managerList.Count; i++)
            {
                int taskcount = 0;
                string toemail="";
                string html = managerhtml(managerList[i], tasks,out taskcount,out toemail);
                if (taskcount > 0)
                {
                    html = managerList[i] + " 您好，截止" + currentTime.ToShortDateString() + " 24时，您下属共有" + taskcount.ToString() + "个过期未完成任务<br/>" + html;
                    html += "<br/>" + "<a href='" + PMSite + "'>" + "点击查看" + "</a>";
                    SendEmail(toemail, managerList[i], "每日邮件提醒", html);
                }
            }
        }
        public void SendWeeklyEmail(DateTime currentTime)
        {

            DateTime weekstart = currentTime.AddDays(-7);
            DateTime nextweekstart = currentTime;
            DateTime nextweekend = nextweekstart.AddDays(7);
            string Sql = "select a.*,b.projectcode from task a inner join project b on a.projectid=b.id and b.IsActived =1  inner join TaskState c on a.TaskStateID=c.id and c.code=30 where a.enddate<='" + currentTime.ToShortDateString() + "' and a.enddate>='" + weekstart.ToShortDateString() + "'  order by b.projectcode,a.startdate";
            DataTable tasks1 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);
            Sql = "select a.*,b.projectcode from task a  inner join project b on a.projectid=b.id and b.IsActived =1  inner join TaskState c on a.TaskStateID=c.id where a.startdate<='" + nextweekend.ToShortDateString() + "' and a.startdate>='" + nextweekstart.ToShortDateString() + "'  order by b.projectcode,a.startdate";
            DataTable tasks2 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);

            List<string> ownerList = new List<string>();
            for (int i = 0; i < tasks1.Rows.Count; i++)
            {
                string owner = tasks1.Rows[i]["Owners"].ToString();
                List<string> temp = owner.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!ownerList.Contains(temp[k]))
                        ownerList.Add(temp[k]);
                }
            }
            for (int i = 0; i < tasks2.Rows.Count; i++)
            {
                string owner = tasks2.Rows[i]["Owners"].ToString();
                List<string> temp = owner.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!ownerList.Contains(temp[k]))
                        ownerList.Add(temp[k]);
                }
            }

            for (int i = 0; i < ownerList.Count; i++)
            {
                int currenttaskcount = 0;
                int nexttaskcount = 0;
                string toemail = "";
                //本周
                string html = ownerhtml(ownerList[i],tasks1,out currenttaskcount,out toemail);
                
                if (currenttaskcount >= 0)
                {
                    html = ownerList[i] + " 您好，截止" + currentTime.ToShortDateString() + " 24时，本周您共有" + currenttaskcount.ToString() + "个过期未完成任务<br/>" + html;
                }
                //下周
                string html2 = ownerhtml(ownerList[i], tasks2, out nexttaskcount, out toemail);
                
                if (nexttaskcount >= 0)
                {
                    html2 = "<br/>下周您共有" + nexttaskcount.ToString() + "个任务<br/>" + html2;
                }
                if (currenttaskcount > 0 || nexttaskcount > 0)
                {
                    html = html + html2;
                    html += "<br/>" + "<a href='" + PMSite + "'>" + "点击查看" + "</a>";
                    SendEmail(toemail, ownerList[i], "每周邮件提醒", html);
                }
            }


            Sql = "select a.*,b.manager,b.projectcode from task a inner join project b on a.projectid=b.id and b.IsActived =1   inner join TaskState c on a.TaskStateID=c.id and c.code=30  where a.enddate<='" + currentTime.ToShortDateString() + "' and a.enddate>='" + weekstart.ToShortDateString() + "' order by b.projectcode,a.startdate";
            tasks1 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);
            Sql = "select a.*,b.manager,b.projectcode from task a inner join project b on a.projectid=b.id and b.IsActived =1   inner join TaskState c on a.TaskStateID=c.id  where a.startdate<='" + nextweekend.ToShortDateString() + "' and a.startdate>='" + nextweekstart.ToShortDateString() + "' order by b.projectcode,a.startdate";
            tasks2 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);

            List<string> managerList = new List<string>();
            for (int i = 0; i < tasks1.Rows.Count; i++)
            {
                string manager = tasks1.Rows[i]["manager"].ToString().ToUpper();
                List<string> temp = manager.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!managerList.Contains(temp[k]))
                        managerList.Add(temp[k]);
                }
            }
            for (int i = 0; i < tasks2.Rows.Count; i++)
            {
                string manager = tasks2.Rows[i]["manager"].ToString().ToUpper();
                List<string> temp = manager.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!managerList.Contains(temp[k]))
                        managerList.Add(temp[k]);
                }
            }

            for (int i = 0; i < managerList.Count; i++)
            {
                int currenttaskcount = 0;
                int nexttaskcount = 0;
                string toemail = "";
                //本周
                string html = managerhtml(managerList[i], tasks1, out currenttaskcount, out toemail);

                if (currenttaskcount >= 0)
                {
                    html = managerList[i] + " 您好，截止" + currentTime.ToShortDateString() + " 24时，本周您下属共有" + currenttaskcount.ToString() + "个过期未完成任务<br/>" + html;
                }
                string html2 = managerhtml(managerList[i], tasks2, out nexttaskcount, out toemail);
                
                if (nexttaskcount >= 0)
                {
                    html2 = "<br/>下周您下属共有" + nexttaskcount.ToString() + "个任务<br/>" + html2;
                }
                if (currenttaskcount > 0 || nexttaskcount > 0)
                {
                    html = html + html2;
                    html += "<br/>" + "<a href='" + PMSite + "'>" + "点击查看" + "</a>";
                    SendEmail(toemail, managerList[i], "每周邮件提醒", html);
                }
            }
        }
        public void SendMonthlyEmail(DateTime currentTime)
        {
            DateTime monthstart = currentTime.AddMonths(-1);
            DateTime monthend = currentTime.AddDays(-1);
            DateTime nextmonthstart = currentTime;
            DateTime nextmonthend = currentTime.AddMonths(1).AddDays(-1);
            string Sql = "select a.*,b.projectcode from task a left join project b on a.projectid=b.id and b.IsActived =1  inner join TaskState c on a.TaskStateID=c.id and c.code=30 where a.enddate<='" + monthend.ToShortDateString() + "' and a.enddate>='" + monthstart.ToShortDateString() + "'  order by b.projectcode,a.startdate";
            DataTable tasks1 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);
            Sql = "select  a.*,b.projectcode from task a left join project b on a.projectid=b.id and b.IsActived =1  inner join TaskState c on a.TaskStateID=c.id where a.startdate<='" + nextmonthend.ToShortDateString() + "' and a.startdate>='" + nextmonthstart.ToShortDateString() + "' order by b.projectcode,a.startdate";
            DataTable tasks2 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);

            List<string> ownerList = new List<string>();
            for (int i = 0; i < tasks1.Rows.Count; i++)
            {
                string owner = tasks1.Rows[i]["Owners"].ToString();
                List<string> temp = owner.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!ownerList.Contains(temp[k]))
                        ownerList.Add(temp[k]);
                }
            }
            for (int i = 0; i < tasks2.Rows.Count; i++)
            {
                string owner = tasks2.Rows[i]["Owners"].ToString();
                List<string> temp = owner.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!ownerList.Contains(temp[k]))
                        ownerList.Add(temp[k]);
                }
            }

            for (int i = 0; i < ownerList.Count; i++)
            {
                int currenttaskcount = 0;
                int nexttaskcount = 0;
                string toemail = "";
                //本月
                string html = ownerhtml(ownerList[i], tasks1,out currenttaskcount, out toemail);
                
                if (currenttaskcount >= 0)
                {
                    html = ownerList[i] + " 您好，截止" + currentTime.AddDays(-1).ToShortDateString() + " 24时，本月您共有" + currenttaskcount.ToString() + "个过期未完成任务<br/>" + html;
                }
                //下月
                string html2 = ownerhtml(ownerList[i], tasks2, out nexttaskcount, out toemail);
                
                if (nexttaskcount >= 0)
                {
                    html2 = "<br/>下月您共有" + nexttaskcount.ToString() + "个任务<br/>" + html2;

                }
                if (currenttaskcount > 0 || nexttaskcount > 0)
                {
                    html = html + html2;
                    html += "<br/>" + "<a href='" + PMSite + "'>" + "点击查看" + "</a>";
                    SendEmail(toemail, ownerList[i], "每月邮件提醒", html);
                }
            }


            Sql = "select a.*,b.manager,b.projectcode from task a inner join project b on a.projectid=b.id and b.IsActived =1   inner join TaskState c on a.TaskStateID=c.id and c.code=30  where a.enddate<='" + monthend.ToShortDateString() + "' and a.enddate>='" + monthstart.ToShortDateString() + "'  order by b.projectcode,a.startdate";
            tasks1 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);
            Sql = "select a.*,b.manager,b.projectcode from task a inner join project b on a.projectid=b.id and b.IsActived =1   inner join TaskState c on a.TaskStateID=c.id  where a.startdate<='" + nextmonthend.ToShortDateString() + "' and a.startdate>='" + nextmonthstart.ToShortDateString() + "'  order by b.projectcode,a.startdate";
            tasks2 = SqlHelper.GetDataTable(SqlHelper.ConnectionStringPM, CommandType.Text, Sql);

            List<string> managerList = new List<string>();
            for (int i = 0; i < tasks1.Rows.Count; i++)
            {
                string manager = tasks1.Rows[i]["manager"].ToString().ToUpper();
                List<string> temp = manager.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!managerList.Contains(temp[k]))
                        managerList.Add(temp[k]);
                }
            }
            for (int i = 0; i < tasks2.Rows.Count; i++)
            {
                string manager = tasks2.Rows[i]["manager"].ToString().ToUpper();
                List<string> temp = manager.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                for (int k = 0; k < temp.Count; k++)
                {
                    if (!managerList.Contains(temp[k]))
                        managerList.Add(temp[k]);
                }
            }

            for (int i = 0; i < managerList.Count; i++)
            {
                int currenttaskcount = 0;
                int nexttaskcount = 0;
                string toemail = "";
                //本月
                string html = managerhtml(managerList[i],tasks1,out currenttaskcount,out toemail);
                
                if (currenttaskcount >= 0)
                {
                    html = managerList[i] + " 您好，截止" + currentTime.AddDays(-1).ToShortDateString() + " 24时，本月您下属共有" + currenttaskcount.ToString() + "个过期未完成任务<br/>" + html;
                }
                string html2 = managerhtml(managerList[i], tasks2, out nexttaskcount, out toemail);
                
                if (nexttaskcount >= 0)
                {
                    html2 = "<br/>下月您下属共有" + nexttaskcount.ToString() + "个任务<br/>" + html2;

                }
                if (currenttaskcount > 0 || nexttaskcount > 0)
                {
                    html = html + html2;
                    html += "<br/>" + "<a href='" + PMSite + "'>" + "点击查看" + "</a>";
                    SendEmail(toemail, ownerList[i], "每月邮件提醒", html);
                }
            }
        }

        public string ownerhtml(string owner, DataTable tasks, out int taskcount, out string toemail)
        {
            taskcount = 0;
            toemail = "";
            string html = "";
            html = "<table width='740' border='1' cellspacing='0' cellpadding='2' style='font-size:14px; font-family:microsoft yaHei; border:1px solid #ccc; border-collapse:collapse; line-height:20px;'>";
            html += "<tr style='background:#990134; height:30px; line-height:30px; color: #fff;'>";
            html += "<th width='400' scope='col'><strong>任务名称</strong></th>";
            html += "<th width='80' scope='col'><strong>项目Code</strong></th>";
            html += "<th width='130' scope='col'><strong>开始时间</strong></th>";
            html += "<th width='130' scope='col'><strong>原定完成时间</strong></th>";
            html += "</tr>";
            string Sql = "select [Email] from EmployeeRole where [AccountName]='" + owner + "' and [Email] is not null";
            DataTable emailDT = SqlHelper.GetDataTable(SqlHelper.ConnectionStringSales, CommandType.Text, Sql);
            if (emailDT.Rows.Count == 0)
                return "";
            toemail = emailDT.Rows[0][0].ToString();
            int index = 0;
            for (int k = 0; k < tasks.Rows.Count; k++)
            {
                string owners = tasks.Rows[k]["Owners"].ToString();
                List<string> temp = owners.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (temp.Contains(owner))
                {
                    taskcount++;
                    if (index % 2 == 0)
                        html += "<tr style='background:#fff;'>";
                    else
                        html += "<tr style='background:#fff1f6;'>";
                    html += "<td>" + tasks.Rows[k]["Name"].ToString() + "</td>";
                    html += "<td>" + tasks.Rows[k]["projectcode"].ToString() + "</td>";
                    html += "<td>" + DateTime.Parse(tasks.Rows[k]["StartDate"].ToString()).ToShortDateString() + "</td>";
                    html += "<td>" + DateTime.Parse(tasks.Rows[k]["EndDate"].ToString()).ToShortDateString() + "</td>";
                    html += "</tr>";
                    index++;
                }

            }
            html += "</table>";
            return html;
        }
        public string managerhtml(string manager, DataTable tasks, out int taskcount, out string toemail)
        {
            taskcount = 0;
            toemail = "";
            string html = "";
            html = "<table width='704' border='1' cellspacing='0' cellpadding='2' style='font-size:14px; font-family:microsoft yaHei; border:1px solid #ccc; border-collapse:collapse; line-height:20px;'>";
            html += "<tr style='background:#990134; height:30px; line-height:30px; color: #fff;'>";
            html += "<th width='300' scope='col'><strong>任务名称</strong></th>";
            html += "<th width='80' scope='col'><strong>项目Code</strong></th>";
            html += "<th width='112' scope='col'><strong>开始时间</strong></th>";
            html += "<th width='112' scope='col'><strong>原定完成时间</strong></th>";
            html += "<th width='100' scope='col'><strong>执行人</strong></th>";
            html += "</tr>";
            string Sql = "select [Email] from EmployeeRole where [AccountName]='" + manager + "' and [Email] is not null";
            DataTable emailDT = SqlHelper.GetDataTable(SqlHelper.ConnectionStringSales, CommandType.Text, Sql);
            if (emailDT.Rows.Count == 0)
                return "";
            toemail = emailDT.Rows[0][0].ToString();
            int index1 = 0;
            for (int k = 0; k < tasks.Rows.Count; k++)
            {
                string managers = tasks.Rows[k]["manager"].ToString().ToUpper();
                List<string> temp = managers.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (temp.Contains(manager))
                {
                    taskcount++;
                    if (index1 % 2 == 0)
                        html += "<tr style='background:#fff;'>";
                    else
                        html += "<tr style='background:#fff1f6;'>";
                    html += "<td style=\"word-break:break-all; word-wrap:break-word;\">" + tasks.Rows[k]["Name"].ToString() + "</td>";
                    html += "<td >" + tasks.Rows[k]["ProjectCode"].ToString() + "</td>";
                    html += "<td>" + DateTime.Parse(tasks.Rows[k]["StartDate"].ToString()).ToShortDateString() + "</td>";
                    html += "<td>" + DateTime.Parse(tasks.Rows[k]["EndDate"].ToString()).ToShortDateString() + "</td>";
                    html += "<td style=\"word-break:break-all; word-wrap:break-word;\">" + tasks.Rows[k]["Owners"].ToString() + "</td>";
                    html += "</tr>";
                    index1++;
                }
            }
            html += "</table>";
            return html;
        }
        public static bool SendEmail(string toEmail, string toName, string subject, string content)
        {
            //toEmail = "ericzh@cdmc.org.cn";
            //toEmail = "comeonliuqd@163.com";
            // Send email
            SmtpClient smtp = new SmtpClient();
            smtp.Host = ConfigurationManager.AppSettings["SMTP_Server"].ToString();
            smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTP_Port"].ToString());
            NetworkCredential SMTPUserInfo = new NetworkCredential(ConfigurationManager.AppSettings["SMTP_Username"].ToString(), ConfigurationManager.AppSettings["SMTP_Password"].ToString());
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = SMTPUserInfo;

            //MailAddress from = new MailAddress("system@cdmc.org.cn", "system@cdmc.org.cn", System.Text.Encoding.Unicode);
            MailAddress from = new MailAddress(SMTPUserInfo.UserName, "系统邮件提醒", System.Text.Encoding.UTF8);
            MailAddress to = new MailAddress(toEmail, toName, System.Text.Encoding.UTF8);
            MailMessage message = new MailMessage(from, to);
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.Subject = subject;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Body = content;
            message.IsBodyHtml = true;

            try
            {
                smtp.Send(message);
                return true;
            }
            catch(Exception e)
            {
                LogHandle.WriteErrorLog(e);
                return false;
            }
            finally { message.Dispose(); smtp.Dispose(); }

        }
    }
}
